import datetime
from dataclasses import dataclass, field
from typing import Self  # type: ignore

from src.application.user.enums import LangCode
from src.domain.common.entities import AggregateRoot
from src.domain.order.entities.proxy import ProxyEntity
from src.domain.user.entities.allowed_ip import AllowedIpEntity
from src.domain.user.value_objects import UserId
from src.domain.user.value_objects.telegram_user_id import TelegramUserId
from src.domain.user.value_objects.user_email import UserEmail


@dataclass
class UserAggregate(AggregateRoot):
    """Полная модель пользователя"""

    id: UserId
    tg_id: TelegramUserId
    username: str
    email: UserEmail | None = None
    balance: float = 0
    is_registered: bool = field(default=False)
    proxies: list[ProxyEntity] = field(default_factory=list)
    lang_code: LangCode = LangCode.ru
    allowed_ips: list[AllowedIpEntity] = field(default_factory=list)
    test_proxy_acquired: datetime.datetime | None = None
    was_registered: datetime.datetime | None = None

    @classmethod
    def create_user(
        cls,
        *,
        telegram_id: TelegramUserId,
        username: str,
    ) -> Self:
        """
        Создание модели пользователя
        """
        user = UserAggregate(
            id=UserId(0),  # TODO Потом заменить на uuid
            tg_id=telegram_id,
            username=username,
        )

        return user

    def register_user(self, email: UserEmail):
        """Регистрируем пользователя в боте"""

        self.is_registered = True
        self.email = email

    def increase_balance(self, amount: float):
        """Увеличиваем баланс пользователя"""

        self.balance += amount

    def decrease_balance(self, amount: float):
        """Уменьшаем баланс пользователя"""

        # TODO Добавить проверку на нулевой баланс
        self.balance -= amount

    def set_test_proxy_acquired(self, *, test_proxy_acquired: datetime.datetime):
        """Обновление test_proxy_acquired"""

        self.test_proxy_acquired = test_proxy_acquired

    def add_proxies(self, proxies: list[ProxyEntity]):
        """Добавляем прокси пользователю"""

        for proxy in proxies:
            self.proxies.append(proxy)

    def delete_proxies(self, proxies_to_delete: list[ProxyEntity]):
        """Удаляем прокси у пользователя"""

        self.proxies = [proxy for proxy in self.proxies if proxy not in proxies_to_delete]

    def set_language(self, lang_code: LangCode) -> None:
        """Меняем язык пользователя"""

        self.lang_code = lang_code

    def create_allowed_ip(self, user_id: int, ip_address: str):
        """Создаем allowed_ip"""

        self.allowed_ips.append(AllowedIpEntity(user_id=user_id, ip_address=ip_address))
